<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const chartRef = ref()
let chartInstance = null

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)

  chartInstance.setOption({
    title: {
      text: '系统资源使用率',
      left: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}%'
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLine: { lineStyle: { color: '#ccc' } },
      axisLabel: { color: '#fff' }
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLine: { lineStyle: { color: '#ccc' } },
      splitLine: { show: false },
      axisLabel: { color: '#fff' }
    },
    series: [
      {
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#4db3ff'
        },
        barWidth: '40%'
      }
    ],
    grid: {
      top: 50,
      left: 40,
      right: 20,
      bottom: 30
    }
  })
}

// 拉取数据并更新图表
const updateChart = async () => {
  const res = await axios.get('/api/chart/system-status')
  if (res.data.code !== 0) return
  const data = res.data.data

  chartInstance.setOption({
    xAxis: { data: data.map(d => d.name) },
    series: [{ data: data.map(d => d.value) }]
  })
}

onMounted(() => {
  initChart()
  updateChart()

  // const timer = setInterval(updateChart, 5000)
  // onBeforeUnmount(() => clearInterval(timer))
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
